package com.example.project.projectspringcloud.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

/**
 * @ClassName: AliSmsUtil
 * @Author: Blue
 * @Description:
 * @Date: 2022/9/22 10:19
 */
public class AliSmsUtil {
    private static final String ACCESS_KEY = "LTAITidB7KPsvtef";

    private static final String SECRET = "EI8K6wlo9zgWyK2Vmimf9JeuIDWpbZ";

    /**
     * 发送验证短信
     *
     * @param phone phone
     * @param code  验证码
     * @return true为发送成功
     */
    public static boolean sendSms(String phone, String code) throws Exception {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY, SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "巨桃游娱");
        //todo 阿里云短信模板
        request.putQueryParameter("TemplateCode", "SMS_182668335");
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject object = JSON.parseObject(response.getData());
            if ("OK".equals(object.getString("Code"))) {
                return true;
            } else {
                throw new Exception("验证码发送失败:" + object.getString("Message"));
            }
        } catch (ClientException e) {
            throw new Exception("验证码发送失败", e);
        }
    }
}
